import Taro from '@tarojs/taro'
import { USER_TYPE } from '@/utils/enum/common'
import { getUserInfo } from '@/services/my'

// 缓存登录用户信息
export function storeUserInfo(data) {
  if (!data) {
    return
  }
  const userInfo = {
    userId: data.user_id,
    userEnterpriseId: data.user_enterprise_id,
    userType: data.user_type,
    userTypeName: data.user_type_name,
    userName: data.real_name,
    phone: data.phone,
    humanFace: data.human_face,
    defaultEnterpriseId: data.enterprise_id,
    enterprises: data.enterprises
  }
  Taro.setStorageSync('user', JSON.stringify(userInfo))
}

// 获取用户信息
export function getCacheUser() {
  const user = Taro.getStorageSync('user')
  return user ? JSON.parse(user) : null
}

// 获取用户类型
export function getCacheUserType() {
  const user = getCacheUser()
  return user?.userType || ''
}

export function getCacheEnterprise() {
  const user = getCacheUser()
  return user?.enterprises || []
}

export async function checkIsManager() {
  const resp = await getUserInfo()
  return resp?.user_type === USER_TYPE.ADMIN
}

// 获取默认企业ID
export function getCacheDefaultEnterpriseId() {
  const user = getCacheUser()
  return user?.defaultEnterpriseId || ''
}

// 获取默认企业名称
export function getCacheDefaultEnterpriseName() {
  const user = getCacheUser()
  const enterprise_name = user?.enterprises?.find((item) => item.record_id === user?.defaultEnterpriseId)?.name
  return enterprise_name || ''
}

export function checkJoinEnterprise() {
  const enterpriseId = getCacheDefaultEnterpriseId()
  return !!enterpriseId
}

export function checkLogin() {
  const token = Taro.getStorageSync('token')
  return !!token
}

export function getCacheToken() {
  const token = Taro.getStorageSync('token')
  return token
}
